package com.jar.myfourthapp;

import android.app.Application;
import android.content.Context;
import android.net.ProxyInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class settingwifi extends AppCompatActivity {
    private static ProxyInfo minfo;
    private Button btn1;
    private Button btn2;
    private EditText txt1;
    private EditText txt2;
    private TextView txt3;
    public String str1;
    public String str2;
    //    public int str2;
    private String getWifiIp;
    private static List list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settingwifi);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        txt1 = findViewById(R.id.edtext1);
        txt2 = findViewById(R.id.edtext2);
        txt3 = findViewById(R.id.text3);
//        SharedPreferences read = getSharedPreferences("lock", MODE_PRIVATE);
//        String ip = read.getString("ip", "");
//        int port = read.getInt("port", 0);
//        if (!(ip.equals("") & port == 0)) {
//
//        }
        final Application application = getApplication();
        btn1.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                str1 = txt1.getText().toString();
//                str2 = Integer.parseInt(txt2.getText().toString());
                str2 = txt2.getText().toString();
                set_proxy(application, str1, str2, 1);
                System.out.println("输出的问题信息:" + str1 + ":" + str2);
                Toast ts = Toast.makeText(settingwifi.this, "显示当前的输入2" + str1 + str2 + getWifiIp, Toast.LENGTH_LONG);
                ts.show();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void onClick(View v) {
                str1 = txt1.getText().toString();
//                str2 = Integer.parseInt(txt2.getText().toString());
                str2 = txt2.getText().toString();
                try {
//                    getURLConnection(p);
                    set_proxy(application, str1, str2, 0);
//                    unsetWifiProxySettingsFor17And(settingwifi.this);
                    System.out.println("输出信息:" + str1 + str2);
                } catch (Exception e) {
                    System.out.println("输出运行异常：" + e);
                }
            }
        });

    }

    public static Object getField(Object obj, String name)
            throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        Object out = f.get(obj);
        return out;
    }

    // 获取当前的Wifi连接
    public static WifiConfiguration getCurrentWifiConfiguration(WifiManager wifiManager) {
        if (!wifiManager.isWifiEnabled())
            return null;
        List<WifiConfiguration> configurationList = wifiManager.getConfiguredNetworks();
        WifiConfiguration configuration = null;
        int cur = wifiManager.getConnectionInfo().getNetworkId();
//        System.out.println("输出wifi列表返回的信息:" + cur + wifiManager.getConnectionInfo());
        for (int i = 0; i < configurationList.size(); ++i) {
            WifiConfiguration wifiConfiguration = configurationList.get(i);
            if (wifiConfiguration.networkId == cur) {
                configuration = wifiConfiguration;
//                System.out.println("输出wifi列表:::" + configuration + "输出的列表结尾");
            }
        }
        return configuration;

    }

    public static void SettingProxy(Application context, String ip, String prot, int type) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wifiManager.getConnectionInfo();
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        //不走代理名单
        int cur = wi.getNetworkId();
        WifiConfiguration config = null;
        for (int i = 0; i < configuredNetworks.size(); i++) {
            WifiConfiguration wifiConfiguration = configuredNetworks.get(i);
            if (wifiConfiguration.networkId == cur) {
                //需要给哪个无线设置代理
                config = wifiConfiguration;
            }
        }
        try {

        } catch (Exception e) {
            System.out.println("代码输出异常:" + e);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void set_proxy(Application context, String ip, String port, int type) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wifiManager.getConnectionInfo();
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        //不走代理名单
        int cur = wifiManager.getConnectionInfo().getNetworkId();
        WifiConfiguration config = null;
        for (int i = 0; i < configuredNetworks.size(); i++) {
            WifiConfiguration wifiConfiguration = configuredNetworks.get(i);
//            System.out.println("输出wificonfiguration的参数:" + wifiConfiguration);
            if (wifiConfiguration.networkId == cur) {
                //需要给哪个无线设置代理
                config = wifiConfiguration;
            }
        }
//        System.out.println("修改前的config" + config);
        try {
//            System.out.println("能不能确定下来:??" + config);
            Class proxySettings = Class.forName("android.net.IpConfiguration$ProxySettings");
            Class proxy = Class.forName("android.net.Proxy");
            Class[] setProxyParams = new Class[2];
            setProxyParams[0] = proxySettings;
            setProxyParams[1] = ProxyInfo.class;
            System.out.println("写入setProxy的数据：" + setProxyParams[0] + setProxyParams[1]);
            Method setProxy = config.getClass().getDeclaredMethod("setProxy", setProxyParams);
//            System.out.println("是不是这里输出的？？:" + setProxy.toString());
            setProxy.setAccessible(true);
//            System.out.println("是这里？？:" + setProxy);
            if (type == 0) {
                Object[] methodParams = new Object[2];
                methodParams[0] = Enum.valueOf(proxySettings, "NONE");
                ProxyInfo desiredProxy = ProxyInfo.buildDirectProxy("", 0);
                methodParams[1] = desiredProxy;
                setProxy.invoke(config, methodParams);
            } else {
                ArrayList<String> list = new ArrayList<>();
                list.add("*.example.com");
//                Integer.parseInt(port);
                ProxyInfo desiredProxy = ProxyInfo.buildDirectProxy("192.168.1.31", 1333, list);
//                System.out.println("能走到这里？？" + desiredProxy);
                Object[] methodParams = new Object[2];
                System.out.println("proxySettings的参数:" + proxySettings);
//                numAssociation
                methodParams[0] = Enum.valueOf(proxySettings, "STATIC");
                methodParams[1] = desiredProxy;
//                methodParams[2] = 114;
                System.out.println("输出信息:" + methodParams[0] + methodParams[1]);
                setProxy.invoke(config, methodParams);
            }
            System.out.println("修改完毕的config:" + config);
            //save the settings
            System.out.println("输出confignewtid:" + config.networkId);
            if (config == null || config.networkId < 0) {
                System.out.println("传递的信息出错了:" + config == null);
            }
            int result = wifiManager.updateNetwork(config);
            System.out.println("输出更新的network的结果:" + result + config.networkId);
//            int addresult = wifiManager.addNetwork(config);
//            System.out.println("输出add的结果:" + addresult);
            boolean flag1 = wifiManager.reassociate();
            System.out.println("重连network成功:" + flag1);
//            boolean flag1 = wifiManager.disconnect();
//            System.out.println("断开network成功:" + flag1);
//            boolean flag2 = wifiManager.reconnect();
//            System.out.println("重连network成功:" + flag2);
        } catch (Exception e) {
            System.out.println("代码输出异常:" + e);
        }

    }

    //取消代理设置
    public static void unsetWifiProxySettingsFor17And(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wifiManager.getConnectionInfo();
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        int cur = wi.getNetworkId();
        WifiConfiguration config = null;
        for (int i = 0; i < configuredNetworks.size(); i++) {
            WifiConfiguration wifiConfiguration = configuredNetworks.get(i);
            if (wifiConfiguration.networkId == cur) {
                //需要给哪个无线设置代理
                config = wifiConfiguration;
            }
        }
        if (config == null) return;
        try {
            //从WiFi配置获取链接属性
            System.out.println("输出confiog的内容:" + config);
            Object linkProperties = getFieldObject(config, "linkProperties");
            System.out.println("输出返回的object对象:" + linkProperties);
            Class<?> proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
            Class<?>[] setHttpProxyParams = new Class[1];
            setHttpProxyParams[0] = proxyPropertiesClass;
            Class<?> IpClass = Class.forName("android.net.LinkProperties");
            Method setHttpProxy = IpClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
            setHttpProxy.setAccessible(true);
            //pass null as the proxy
            Object[] params = new Object[1];
            params[0] = null;
            setHttpProxy.invoke(linkProperties, params);
            setEnumField(config, "NONE", "proxySettings");
            //save the config
            wifiManager.updateNetwork(config);
            wifiManager.disconnect();
            wifiManager.reconnect();
        } catch (Exception e) {
            System.out.println("输出取消代理异常的返回:" + e);
        }
    }

    // getField只能获取类的public 字段.
    public static Object getFieldObject(Object obj, String name) throws
            SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        Object out = f.get(obj);
        return out;
    }
    // 设置公共成员常量值 

    public static void setEnumField(Object obj, String value, String name) throws
            SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
    }


}

